﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTreeList;
using System.Text.RegularExpressions;
using DevExpress.XtraTreeList.Nodes;

namespace MDIDemo.Modules
{
    public partial class XuatHang : DevExpress.XtraEditors.XtraForm
    {
        String sErr = "";
        DataRow _row = null;
        String IDKH = "";
        int idThem = 29;
        int idXoa = 31;
        void SetPermission()
        {
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = (frmMain)this.Parent.Parent;
                btnThem.Visible = frmMain.IsPermis(idThem, main.CurrentPermis.PERMISSION);
                btnXoa.Visible = frmMain.IsPermis(idXoa, main.CurrentPermis.PERMISSION);
                btnLuu.Visible = frmMain.IsPermis(idThem, main.CurrentPermis.PERMISSION);
            }
        }
        public XuatHang()
        {
            InitializeComponent();
        }

        private void XuatHang_Load(object sender, EventArgs e)
        {
            LoadHangHoa();
            RefresForm("");
            EnabledForm(false);
            SetPermission();
        }

        protected void LoadDSBan()
        {

            gridDSBan.ResetText();
            BUS.NXHANGControl ctr = new BUS.NXHANGControl();

            DataTable dt = ctr.GetByAllByCT(txtCT.Text == "" ? "-1" : txtCT.Text, (DateTime)txtNgay.EditValue, null, ref sErr);
            gridDSBan.DataSource = dt;
        }

        protected void LoadHangHoa()
        {
            BUS.NHOMHANGControl ctr = new BUS.NHOMHANGControl();
            tlHangHoa.DataSource = ctr.GetTreeList("", ref sErr);
            tlHangHoa.ExpandAll();
        }

        private void treeList1_MouseClick(object sender, MouseEventArgs e)
        {
            //TreeListHitInfo hit = treeList1.CalcHitInfo(new Point(e.X, e.Y));
            //if (hit.Node != null && hit.Node.Id > 0)
            //{
            //    MessageBox.Show(hit.Node.GetValue("NHOMHANG").ToString());
            //}
        }

        private void treeList1_FocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e)
        {
            if (e.Node != null)
            {
                LoadTonKho(e.Node);
            }
        }

        private void LoadTonKho(TreeListNode node)
        {
            BUS.LOAIHANGControl ctr = new BUS.LOAIHANGControl();
            gridSanPham.DataSource = ctr.GetTonKho(node.GetValue("ParentID").ToString(), node.GetValue("ID").ToString(), 0, null, ref sErr);
        }
        protected void TinhTongCong()
        {
            Double kq = 0;

            DataTable dt = (DataTable)gridDSBan.DataSource;
            foreach (DataRow row in dt.Rows)
            {
                kq += Convert.ToDouble(row[DTO.NXHANGInfo.Field.SOTIEN.ToString()].ToString());
            }
            txtTienHang.EditValue = kq;
            txtTienThieu.EditValue = kq + Convert.ToDouble(txtPhiVanChuyen.EditValue) - Convert.ToDouble(txtChieutkhau.EditValue) - Convert.ToDouble(txtTienDatTruoc.EditValue);

            txtTongcong.EditValue = kq + Convert.ToDouble(txtPhiVanChuyen.EditValue) - Convert.ToDouble(txtChieutkhau.EditValue);
        }
        private void btThem_Click(object sender, EventArgs e)
        {
            if (_row != null)
            {

                Double sl = Convert.ToDouble(txtSoLuong.EditValue);
                if (sl == 0)
                {
                    XtraMessageBox.Show("Nhập số lượng");
                    txtSoLuong.EditValue = 0;
                    txtSoLuong.Focus();
                    return;
                }
                DataTable dt = (DataTable)gridDSBan.DataSource;
                //DataRow[] arr = dt.Select("LOAIHANG ='" + txtMaHang.Text + "'");
                //if (arr.Length > 0)
                //{
                //    dt.Rows.Remove(arr[0]);
                //}
                if (dt.Rows.Count >= 15)
                {
                    XtraMessageBox.Show("Nhập quá 15 dòng.");
                    btnLuu.Focus();
                    return;
                }

                DTO.TONKHOInfo tonkhoinf = new DTO.TONKHOInfo(_row);
                DTO.NXHANGInfo inf = new DTO.NXHANGInfo();
                inf.LOAIHANG = txtMaHang.Text;
                inf.SOCT = txtCT.Text;
                //   inf.LINE = dt.Rows.Count + 1;
                inf.LOAICT = "BH001";
                inf.NGAYCT = (DateTime)txtNgay.EditValue;
                inf.QUYCACH = txtQuyCach.Text;
                inf.DVTINH = txtDonViTinh.Text;
                inf.SOLUONG = Convert.ToDouble(txtSoLuong.EditValue);
                inf.GIAVON = tonkhoinf.GIAVON;
                inf.GIABAN = Convert.ToDouble(txtDonGia.EditValue);
                inf.SOTIEN = Convert.ToDouble(txtTongTien.EditValue);
                inf.TINHTRANG = txtTT.Text;
                inf.XUATKHO = true;


                DataRow row = inf.ToDataRow(dt);
                row["TENHANG"] = txtTenHang.Text;
                dt.Rows.Add(row);


                gridDSBan.DataSource = dt;
                TinhTongCong();




            }
        }

        private void RefresForm(string p)
        {
            txtKhachHang.Text = p;
            txtDienThoai.Text = p;
            txtDiaChi.Text = p;
            txtMST.Text = p;
            txtCT.Text = p;
            txtNgay.EditValue = frmMain.__ngayMoSo;
            txtTT.Text = "Normal";
            IDKH = "";
            txtMaHang.Text = p;
            txtTenHang.Text = p;
            txtQuyCach.Text = p;
            txtDonViTinh.Text = p;
            txtSoLuong.EditValue = 0;
            txtDonGia.EditValue = 0;
            txtTongTien.EditValue = 0;

            rgGia.SelectedIndex = 0;
            cbPhiVanChuyen.Checked = false;
            //      cbDatCoc.Checked = false;
            cbChietKhau.Checked = false;
            txtTienDatTruoc.EditValue = 0;
            txtTienThieu.EditValue = 0;
            txtHanMuc.EditValue = 0;
            txtDangNo.EditValue = 0;

            txtTongcong.EditValue = 0;
            txtTienDatTruoc.EditValue = 0;
            txtTienThieu.EditValue = 0;
            txtTienHang.EditValue = 0;
            txtPhiVanChuyen.EditValue = 0;
            txtChieutkhau.EditValue = 0;


            LoadDSBan();
        }

        private void EnabledForm(bool p)
        {
            //txtKhachHang.Enabled = p;
            txtDienThoai.Properties.ReadOnly = !p;
            txtDiaChi.Properties.ReadOnly = !p;
            txtMST.Properties.ReadOnly = !p;
            //txtCT.Properties.ReadOnly = true;
            //txtNgay.Properties.ReadOnly = true;
            //txtTT.Properties.ReadOnly = true;
            //txtDangNo.Properties.ReadOnly = true;
            //txtHanMuc.Properties.ReadOnly = true;
            //txtTenHang.Properties.ReadOnly = true;
            //txtMaHang.Properties.ReadOnly = true;
            //     txtTenHang.Enabled = p;
            txtQuyCach.Properties.ReadOnly = !p;
            //txtDonViTinh.Properties.ReadOnly = true;
            txtSoLuong.Properties.ReadOnly = !p;
            //txtDonGia.Properties.ReadOnly = !p;
            //txtTongTien.Properties.ReadOnly = true;

            rgGia.Properties.ReadOnly = !p;
            cbPhiVanChuyen.Enabled = p;
            if (p == true && cbPhiVanChuyen.Checked)
                txtPhiVanChuyen.Properties.ReadOnly = false;
            else
                txtPhiVanChuyen.Properties.ReadOnly = true;


            //    cbDatCoc.Enabled = p;
            cbChietKhau.Enabled = p;
            if (p == true && cbChietKhau.Checked)
                txtChieutkhau.Properties.ReadOnly = false;
            else
                txtChieutkhau.Properties.ReadOnly = true;

            txtTienDatTruoc.Properties.ReadOnly = !p;
            //       txtTienThieu.Enabled = p;
            //txtTienHang.Properties.ReadOnly = true;
            //txtTongcong.Properties.ReadOnly = true;

            //txtTienThieu.Properties.ReadOnly = true;

            if (frmMain.__khoaSo)
            {
                btnXoa.Enabled = btnThem.Enabled = false;
            }
            else
            {

                btnXoa.Enabled = btnThem.Enabled = !p;
            }
            btnLuu.Enabled = p;
            btnBoQua.Enabled = p;
            btnTimKiem.Enabled = !p;
            btnIn.Enabled = !p;
            btnInCTXNHang.Enabled = !p;
            btnDong.Enabled = !p;

            btKhachHang.Enabled = p;
            btThem.Enabled = p;
            btXoa.Enabled = p;
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            EnabledForm(true);
            RefresForm("");
            BUS.GIAODICHControl ctr = new BUS.GIAODICHControl();
            //DataTable dt = ctr.GetALLByCT(null, null, frmMain.__ngayMoSo, ref sErr);
            //int i = 1;
            //txtCT.Text = (dt.Rows.Count + i).ToString("00000");

            //while (ctr.IsExist(txtCT.Text, null, frmMain.__ngayMoSo))
            //{
            //    txtCT.Text = (dt.Rows.Count + i).ToString("00000");
            //    i++;
            //}
            BUS.CommonControl cmm = new BUS.CommonControl();
            txtCT.Text = cmm.GetSoCTNextNo(frmMain.__ngayMoSo.ToString("yyyy-MM-dd"));

            BUS.CUSTINFOControl cusctr = new BUS.CUSTINFOControl();
            DTO.CUSTINFOInfo cusinf = cusctr.Get("100000000762", ref sErr);
            txtKhachHang.EditValue = cusinf.TENGD;
            IDKH = cusinf.CUSTID;
            SetMaHangInfo();
            gbBanHang.Focus();
            btKhachHang.Focus();
            //btThem.Enabled = true;
            //btXoa.Enabled = true;

            //btnThem.Enabled = false;
        }



        private void gvSanPham_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                if (btnThem.Enabled == false)
                {
                    SetMaHangInfo();
                }
            }
        }

        private void SetMaHangInfo()
        {
            if (gvSanPham.FocusedRowHandle >= 0)
            {
                _row = ((DataRowView)gvSanPham.GetRow(gvSanPham.FocusedRowHandle)).Row;

                txtMaHang.Text = _row["MAHANG"].ToString();
                txtTenHang.Text = _row["TENHANG"].ToString();
                txtQuyCach.Text = _row["QUYCACH"].ToString();
                txtDonViTinh.Text = _row["DVTINH"].ToString();

                txtSoLuong.EditValue = 0;
                txtDonGia.EditValue = 0;
                txtTongTien.EditValue = 0;
            }
        }

        private void txtQuyCach_Leave(object sender, EventArgs e)
        {
            if (txtQuyCach.Text.Contains("x") || txtQuyCach.Text.Contains("X"))
            {
                Double sl = 0;
                String[] s = txtQuyCach.Text.Split(new char[] { 'x', 'X' });
                if (s.Length > 0)
                {
                    sl = 1;
                    for (int i = 0; i < s.Length; i++)
                    {
                        if (s[i] != "")
                        {
                            Double temp = Convert.ToDouble(Regex.Match(s[i].Trim(), "^[0-9]+([.,][0-9]{1,2})?").Value);
                            sl = sl * temp;
                        }
                    }
                }
                txtSoLuong.EditValue = sl;
            }
        }

        private void txtSoLuong_Leave(object sender, EventArgs e)
        {
            if (_row != null)
            {
                if (txtSoLuong.Text != "")
                {

                    Double sl = Convert.ToDouble(txtSoLuong.EditValue);

                    Double slton = Convert.ToDouble(_row[DTO.TONKHOInfo.Field.SOLUONG.ToString()]);
                    Double sldanhap = 0;
                    DataTable dt = (DataTable)gridDSBan.DataSource;
                    DataRow[] arr = dt.Select("LOAIHANG ='" + txtMaHang.Text + "'");
                    if (arr.Length > 0)
                    {
                        foreach (DataRow row in arr)
                        {
                            sldanhap += Convert.ToDouble(row["SOLUONG"].ToString());
                        }
                    }

                    if (sl + sldanhap > slton)
                    {
                        XtraMessageBox.Show("Vượt quá số lượng có trong kho.");
                        txtSoLuong.EditValue = 0;
                        txtSoLuong.Focus();
                        return;
                    }

                    switch (rgGia.SelectedIndex)
                    {
                        case 0:
                            txtDonGia.Text = _row["GIABANLE"].ToString();
                            break;
                        case 1:
                            txtDonGia.Text = _row["GIABANSY"].ToString();
                            break;
                        case 2:
                            txtDonGia.Text = _row["GIABANKHAC"].ToString();
                            break;
                    }
                    txtTongTien.Text = (Convert.ToDouble(txtSoLuong.EditValue) * Convert.ToDouble(txtDonGia.EditValue)).ToString();
                }
            }
        }

        private void rgGia_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_row != null)
            {
                switch (rgGia.SelectedIndex)
                {
                    case 0:
                        txtDonGia.Text = _row["GIABANLE"].ToString();
                        break;
                    case 1:
                        txtDonGia.Text = _row["GIABANSY"].ToString();
                        break;
                    case 2:
                        txtDonGia.Text = _row["GIABANKHAC"].ToString();
                        break;
                }
                txtTongTien.Text = (Convert.ToDouble(txtSoLuong.EditValue) * Convert.ToDouble(txtDonGia.EditValue)).ToString();
            }
        }

        private void btKhachHang_Click(object sender, EventArgs e)
        {
            Windows.frmViewKhachHang kh = new Windows.frmViewKhachHang();
            if (kh.ShowDialog(this) == DialogResult.OK)
            {
                DTO.CUSTINFOInfo inf = new DTO.CUSTINFOInfo(kh.ReturnRow);
                txtKhachHang.Text = inf.TENGD;
                txtDiaChi.Text = inf.DIACHI;
                txtDiaChi.Properties.ReadOnly = true;
                txtDienThoai.Text = inf.DIENTHOAI;
                txtMST.Text = inf.MSTHUE;
                txtHanMuc.EditValue = inf.HMDUNO;
                IDKH = inf.CUSTID;
                txtDangNo.EditValue = TinhCongNo(inf.CUSTID);
                //      txtCT.Text =
                rgGia.SelectedIndex = 1;
                txtDienThoai.Focus();
            }
        }

        protected Double TinhCongNo(String makh)
        {
            Double kq = 0;
            BUS.CONGNOControl ctr = new BUS.CONGNOControl();
            DataTable dt = ctr.GetALLByMaKH(makh, ref sErr);

            foreach (DataRow row in dt.Rows)
            {
                DTO.CONGNOInfo inf = new DTO.CONGNOInfo(row);
                kq += inf.SOTIEN;
            }

            return kq;
        }

        private void cbPhiVanChuyen_CheckedChanged(object sender, EventArgs e)
        {
            if (cbPhiVanChuyen.Checked)
            {
                txtPhiVanChuyen.Properties.ReadOnly = false;

                txtPhiVanChuyen.Focus();
            }
            else
            {
                txtPhiVanChuyen.EditValue = 0;
                txtPhiVanChuyen.Properties.ReadOnly = true;
            }

        }

        private void cbChietKhau_CheckedChanged(object sender, EventArgs e)
        {
            if (cbChietKhau.Checked)
            {
                txtChieutkhau.Properties.ReadOnly = false;
                txtChieutkhau.Focus();
            }
            else
            {
                txtChieutkhau.EditValue = 0;
                txtChieutkhau.Properties.ReadOnly = true;
            }
        }

        private void gvDSBan_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {


                DTO.NXHANGInfo inf = new DTO.NXHANGInfo(((DataRowView)gvDSBan.GetRow(e.FocusedRowHandle)).Row);

                txtTenHang.Text = ((DataRowView)gvDSBan.GetRow(e.FocusedRowHandle)).Row["TENHANG"].ToString();
                txtMaHang.Text = inf.LOAIHANG;
                txtQuyCach.Text = inf.QUYCACH;
                txtDonViTinh.Text = inf.DVTINH;
                txtSoLuong.EditValue = inf.SOLUONG;
                txtDonGia.EditValue = inf.GIABAN;
                txtTongTien.EditValue = inf.SOTIEN;
            }


        }

        private void txtSoLuong_EditValueChanged(object sender, EventArgs e)
        {
            if (txtSoLuong.Text != "")
            {
                txtTongTien.EditValue = (Convert.ToDouble(txtSoLuong.EditValue) * Convert.ToDouble(txtDonGia.EditValue));
            }
        }

        private void btXoa_Click(object sender, EventArgs e)
        {
            int[] s = gvDSBan.GetSelectedRows();
            if (s.Length > 0)
            {
                gvDSBan.DeleteSelectedRows();
                TinhTongCong();
            }
        }

        private void txtPhiVanChuyen_Leave(object sender, EventArgs e)
        {
            TinhTongCong();
        }

        private void txtChieutkhau_Leave(object sender, EventArgs e)
        {
            TinhTongCong();
        }

        private void txtTienDatTruoc_Leave(object sender, EventArgs e)
        {


        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            sErr = "";
            if (IDKH == "")
            {
                XtraMessageBox.Show("Vui lòng nhập thêm thông tin khách hàng", "Thông báo");
                return;
            }
            if (gvDSBan.RowCount == 0)
            {
                XtraMessageBox.Show("Vui lòng nhập thêm thông tin sản phẩm", "Thông báo");
                return;
            }
            sErr = SaveHeader();

            if (sErr == "")
            {
                sErr = SaveDetail();
                if (sErr == "")
                    sErr = SaveCongNo();

            }
            if (sErr != "")
                XtraMessageBox.Show(sErr);
            else
            {
                XtraMessageBox.Show("Lưu thành công");
                //    RefresForm("");
                EnabledForm(false);
                LoadTonKho(tlHangHoa.FocusedNode);
            }

        }

        protected String SaveHeader()
        {
            BUS.GIAODICHControl ctr = new BUS.GIAODICHControl();
            //DataTable dt = ctr.GetALLByCT(null, null, frmMain.__ngayMoSo, ref sErr);
            //int i = 1;
            //txtCT.Text = (dt.Rows.Count + i).ToString("00000");

            //while (ctr.IsExist(txtCT.Text, null, frmMain.__ngayMoSo))
            //{
            //    txtCT.Text = (dt.Rows.Count + i).ToString("00000");
            //    i++;
            //}
            BUS.CommonControl cmm = new BUS.CommonControl();
            txtCT.Text = cmm.GetSoCTNextNo(frmMain.__ngayMoSo.ToString("yyyy-MM-dd"));

            DTO.GIAODICHInfo inf = new DTO.GIAODICHInfo();
            inf.SOCT = txtCT.Text;
            inf.LOAICT = "BH001";
            inf.NGAYCT = (DateTime)txtNgay.EditValue;
            inf.MAKH = IDKH;
            inf.TIENHANG = Convert.ToDouble(txtTienHang.EditValue);
            inf.PHIVC = Convert.ToDouble(txtPhiVanChuyen.EditValue);
            inf.CHIETKHAU = Convert.ToDouble(txtChieutkhau.EditValue);
            inf.TONGTIEN = Convert.ToDouble(txtTongcong.EditValue);

            inf.CONGNO = Convert.ToDouble(txtTienThieu.EditValue);
            inf.THUNGAY = Convert.ToDouble(txtTienDatTruoc.EditValue);
            inf.TIENMAT = inf.THUNGAY;
            inf.LOAITIEN = "VND";
            inf.DIACHIKH = txtDiaChi.Text;
            inf.DIENTHOAI = txtDienThoai.Text;
            inf.NOIDUNG = "Xuất bán cho khách hàng";
            inf.TINHTRANG = txtTT.Text;
            inf.INHD = false;
            inf.CREATEBY = frmMain.__userID;
            inf.MODIFIEDBY = frmMain.__userID;
            inf.CREATEDATE = frmMain.__ngayMoSo;
            inf.MODIFIEDDATE = frmMain.__ngayMoSo;

            ctr.Add(inf, ref sErr);

            return sErr;
        }


        protected String SaveDetail()
        {
            BUS.LOAIHANGControl lhctr = new BUS.LOAIHANGControl();
            BUS.TONKHOControl tonkhoctr = new BUS.TONKHOControl();
            BUS.NXHANGControl ctr = new BUS.NXHANGControl();
            DataTable dt = (DataTable)gridDSBan.DataSource;
            int line = 1;
            foreach (DataRow row in dt.Rows)
            {
                DTO.NXHANGInfo inf = new DTO.NXHANGInfo(row);

                inf.SOCT = txtCT.Text;
                inf.LOCATION = "0001";
                inf.LINE = line;
                ctr.Add(inf, ref sErr);
                if (sErr == "")
                {
                    DTO.LOAIHANGInfo lhinf = lhctr.Get(inf.LOAIHANG, ref sErr);
                    DTO.TONKHOInfo tkinf = new DTO.TONKHOInfo();
                    tkinf = tonkhoctr.Get(lhinf.NHOMHANG, lhinf.MAHANG, ref sErr);
                    tkinf.MODIFIEDBY = frmMain.__userID;
                    tkinf.MODIFIEDDATE = DateTime.Now;
                    tkinf.SOLUONG = tkinf.SOLUONG - inf.SOLUONG;
                    tkinf.SOTIEN = tkinf.SOLUONG * tkinf.GIAVON;
                    tonkhoctr.Update(tkinf);
                    line++;
                }

            }

            return sErr;
        }

        protected String SaveCongNo()
        {
            BUS.CONGNOControl ctr = new BUS.CONGNOControl();
            DTO.CONGNOInfo inf = new DTO.CONGNOInfo();

            inf.SOCT = txtCT.Text;
            inf.NGAYCT = (DateTime)txtNgay.EditValue;
            inf.DIACHIKH = txtDiaChi.Text;
            inf.DIENTHOAI = txtDienThoai.Text;
            inf.PHAITHU = true;
            inf.D_C = "C";
            inf.SOTIEN = Convert.ToDouble(txtTongcong.EditValue);
            inf.NOIDUNG = "Xuất bán cho khách hàng";
            inf.MAKH = IDKH;
            inf.SOCTTT = txtCT.Text;
            inf.SOCTTT = "BH";
            inf.CREATEBY = frmMain.__userID;
            inf.MODIFIEDBY = frmMain.__userID;
            inf.CREATEDATE = frmMain.__ngayMoSo;
            inf.MODIFIEDDATE = frmMain.__ngayMoSo;

            ctr.Add(inf, ref sErr);

            // tra truoc
            if (Convert.ToInt32(txtTienDatTruoc.EditValue) > 0)
            {
                inf.PHAITHU = false;
                inf.D_C = "N";
                inf.SOTIEN = Convert.ToDouble(txtTienDatTruoc.EditValue) * (-1);
                inf.NOIDUNG = "Khách hàng trả trước";
                ctr.Add(inf, ref sErr);
            }



            return sErr;
        }

        private void btnBoQua_Click(object sender, EventArgs e)
        {
            RefresForm("");
            EnabledForm(false);

        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Bạn có thực sự muốn xóa", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                sErr = DeleteHeader(txtCT.Text, (DateTime)txtNgay.EditValue);
                if (sErr == "")
                {
                    sErr = DeleteDetail(txtCT.Text, (DateTime)txtNgay.EditValue);
                    if (sErr == "")
                    {
                        sErr = DeleteCongNo(txtCT.Text, (DateTime)txtNgay.EditValue);
                    }
                }
                if (sErr != "")
                    XtraMessageBox.Show(sErr);
                else
                {
                    RefresForm("");
                    EnabledForm(false);
                }
            }
        }

        protected String DeleteHeader(String ct, DateTime ngay)
        {
            BUS.GIAODICHControl ctr = new BUS.GIAODICHControl();
            sErr = ctr.Delete(ct, "BH001", ngay);

            return sErr;
        }

        protected String DeleteDetail(String ct, DateTime ngay)
        {
            BUS.TONKHOControl tonkhoctr = new BUS.TONKHOControl();
            BUS.LOAIHANGControl lhctr = new BUS.LOAIHANGControl();
            BUS.NXHANGControl ctr = new BUS.NXHANGControl();
            DataTable dt = ctr.GetByAllByCT(ct, ngay, "BH001", ref sErr);

            foreach (DataRow row in dt.Rows)
            {
                DTO.NXHANGInfo inf = new DTO.NXHANGInfo(row);
                sErr = ctr.Delete(ct, inf.LINE, inf.LOAICT, inf.NGAYCT);
                if (sErr == "")
                {
                    DTO.LOAIHANGInfo lhinf = lhctr.Get(inf.LOAIHANG, ref sErr);
                    DTO.TONKHOInfo tkinf = new DTO.TONKHOInfo();
                    tkinf = tonkhoctr.Get(lhinf.NHOMHANG, lhinf.MAHANG, ref sErr);
                    tkinf.SOLUONG = tkinf.SOLUONG + inf.SOLUONG;
                    tkinf.SOTIEN = tkinf.SOLUONG * tkinf.GIAVON;
                    tonkhoctr.Update(tkinf);
                }
            }

            return sErr;
        }

        protected String DeleteCongNo(String ct, DateTime ngay)
        {
            BUS.CONGNOControl ctr = new BUS.CONGNOControl();
            DataTable dt = ctr.GetALLByCT(ct, ngay, ref sErr);

            foreach (DataRow row in dt.Rows)
            {
                DTO.CONGNOInfo inf = new DTO.CONGNOInfo(row);
                sErr = ctr.Delete(inf.ID);
            }

            return sErr;
        }

        private void btnTimKiem_Click(object sender, EventArgs e)
        {
            Windows.frmViewGiaoDich gd = new Windows.frmViewGiaoDich();
            gd.LoaiCT = "BH001";
            if (gd.ShowDialog(this) == DialogResult.OK)
            {
                DTO.GIAODICHInfo inf = new DTO.GIAODICHInfo(gd.ReturnRow);

                txtCT.Text = inf.SOCT;
                txtNgay.EditValue = inf.NGAYCT;
                IDKH = inf.MAKH;
                BUS.CUSTINFOControl ctr = new BUS.CUSTINFOControl();
                DTO.CUSTINFOInfo infCus = ctr.Get(IDKH, ref sErr);
                txtKhachHang.Text = infCus.TENGD;

                txtTienHang.EditValue = inf.TIENHANG;
                txtPhiVanChuyen.EditValue = inf.PHIVC;
                cbPhiVanChuyen.Checked = inf.PHIVC > 0;
                txtChieutkhau.EditValue = inf.CHIETKHAU;
                cbChietKhau.Checked = inf.CHIETKHAU > 0;
                txtTongcong.EditValue = inf.TONGTIEN;
                txtTienThieu.EditValue = inf.CONGNO;
                txtTienDatTruoc.EditValue = inf.THUNGAY;

                txtDiaChi.Text = inf.DIACHIKH;
                txtDienThoai.Text = inf.DIENTHOAI;
                txtTT.EditValue = inf.TINHTRANG;

                LoadDSBan();
                btThem.Enabled = true;
                btXoa.Enabled = true;

                //    btnThem.Enabled = false;
                EnabledForm(false);
            }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void gvDSBan_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                DTO.NXHANGInfo inf = new DTO.NXHANGInfo(((DataRowView)gvDSBan.GetRow(e.RowHandle)).Row);

                txtTenHang.Text = ((DataRowView)gvDSBan.GetRow(e.RowHandle)).Row["TENHANG"].ToString();
                txtMaHang.Text = inf.LOAIHANG;
                txtQuyCach.Text = inf.QUYCACH;
                txtDonViTinh.Text = inf.DVTINH;
                txtSoLuong.EditValue = inf.SOLUONG;
                txtDonGia.EditValue = inf.GIABAN;
                txtTongTien.EditValue = inf.SOTIEN;
            }
        }

        private void gvSanPham_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (btnThem.Enabled == false)
            {
                SetMaHangInfo();
                txtSoLuong.Focus();
            }

        }

        private void báoCáoToolStripMenuItem_Click(object sender, EventArgs e)
        {


        }

        private void gvSanPham_DoubleClick(object sender, EventArgs e)
        {

        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = this.Parent.Parent as frmMain;

                DataSet ds = BuildDataSourcePhieuDatHang();
                BUS.GIAODICHControl ctr = new BUS.GIAODICHControl();
                DTO.GIAODICHInfo inf = ctr.Get(txtCT.Text, "BH001", Convert.ToDateTime(txtNgay.EditValue), ref sErr);
                BUS.PODControl uctr = new BUS.PODControl();
                DTO.PODInfo uInf = uctr.Get(inf.CREATEBY, ref sErr);
                Dictionary<string, object> val = new Dictionary<string, object>();
                val.Add("UserID", uInf.USER_ID);
                val.Add("UserName", uInf.USER_NAME);
                main.ShowReport(ds, "PDH", "Phiếu đặt hàng", val);


                inf.INHD = true;
                ctr.Update(inf);
            }
        }

        public DataSet BuildDataSourcePhieuDatHang()
        {
            DataSet _ds = null;
            string query = @"exec procGIAODICH_phieudathang @SOCT='{0}',@NGAYCT='{1:yyyy-MM-dd}'";
            query = string.Format(query, txtCT.EditValue, txtNgay.EditValue);
            BUS.CommonControl ctr = new BUS.CommonControl();
            _ds = ctr.executeSelectQueries(query);
            return _ds;
        }

        private void btnInCTXNHang_Click(object sender, EventArgs e)
        {
            if (gvSanPham.FocusedRowHandle > -1)
            {
                if (this.Parent.Parent is frmMain)
                {
                    _row = ((DataRowView)gvSanPham.GetRow(gvSanPham.FocusedRowHandle)).Row;
                    frmMain main = this.Parent.Parent as frmMain;
                    Windows.Report.frmBaoCaoCTNXHang frm = new Windows.Report.frmBaoCaoCTNXHang();
                    frm.Mahang = _row["MAHANG"].ToString();

                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        main.ShowReport(frm.DataSource, "BKCTXNH", "Bảng kê chi tiết nhập xuất hàng");
                    }
                }
            }
        }

        private void txtSoLuong_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {

        }

        private void txtPhiVanChuyen_Validated(object sender, EventArgs e)
        {
            TinhTongCong();
        }

        private void txtChieutkhau_Validated(object sender, EventArgs e)
        {
            TinhTongCong();
        }

        private void txtTienDatTruoc_Validated(object sender, EventArgs e)
        {
            TinhTongCong();
        }

        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            btnInCTXNHang_Click(null, null);
        }

        private void txtDiaChi_Validated(object sender, EventArgs e)
        {
            if (txtDiaChi.Properties.ReadOnly == false)
                txtDiaChi.Text = txtDiaChi.Text.ToUpper();
        }

        private void XuatHang_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                if (btnBoQua.Enabled)
                    btnBoQua_Click(null, null);

            }
            else if (e.KeyCode == Keys.F7)
            {
                if (btnLuu.Enabled)
                    btnLuu_Click(null, null);

            }
        }

        private void txtSoLuong_MouseUp(object sender, MouseEventArgs e)
        {
            SpinEdit spinEdit1 = ((SpinEdit)sender);
            spinEdit1.SelectAll();
        }



    }
}